//
//  LKMyCommitApplyViewController.m
//  YLHelper
//
//  Created by she1323 on 2018/5/10.
//  Copyright © 2018年 she1323. All rights reserved.
//

#import "LKMyCommitApplyViewController.h"
#import "LKMyCommitApplyCell.h"
#import "LKPopChoiceView.h"
#import "LKMyAddContinuInvestViewController.h"
#import "LKMyUpdateCustomerViewController.h"
#import "LKMyWaitingCheckCell.h"
#import "LKMyUpdateCustomerCheckViewController.h"
#import "LKMyChooseCheckTypeViewController.h"
#import "LKApprovaModel.h"
#import "LKMyWorkerCheckViewController.h"
#import "LKMyOrderCheckDetailViewController.h"
#import "LKMyUpdateCustomerCheckResultViewController.h"
typedef enum cellStatu{
    CELLMYCOMMIT,
    CELLWAITMYCHECK,
    CELLALREADCHECKED,
    CELLALL,
}cellStatu_Style;


@interface LKMyCommitApplyViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)LKBaseTableview *tableView;
@property(nonatomic,strong)UIView *bgView;
@property(nonatomic,strong)LKPopChoiceView *choiceView;
@property(nonatomic,strong)LKBaseButton *titleBtn;
@property(nonatomic,assign)cellStatu_Style cellStatu;
@property(nonatomic,strong)NSMutableArray *dataListArray;
@property(nonatomic,assign)NSInteger PageIndex;
@property(nonatomic,assign)NSInteger MaxResultCount;
@end

@implementation LKMyCommitApplyViewController

-(LKBaseTableview *)tableView{
    if (!_tableView) {
        _tableView = [LKBaseTableview setTableviewWithFrame:CGRectMake(0, 12 + NAVIGATION_BAR_HEIGHT, WIDTH, HEIGHT - (NAVIGATION_BAR_HEIGHT + 12)) style:UITableViewStyleGrouped registercellClasss:@[@"LKMyCommitApplyCell",@"LKMyWaitingCheckCell"]];
        [self.view addSubview:_tableView];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.emptyDataSetSource = self;
        _tableView.emptyDataSetDelegate = self;
        _cellStatu = CELLMYCOMMIT;
    }
    return _tableView;
}
/**
 头部下拉刷新
 */
-(void)headerReloadData{
    self.PageIndex = 1;
    [self getMyCheckInforWithTitle:self.titleBtn.titleLabel.text];
}

/**
 尾部上拉加载更多
 */
-(void)footerReloadData{
    self.PageIndex++;
    [self getMyCheckInforWithTitle:self.titleBtn.titleLabel.text];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.PageIndex = 1;
    self.MaxResultCount = 30;
    [self getMyCheckInforWithTitle:@""];
    self.tableView.estimatedRowHeight = 200;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerReloadData)];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerReloadData)];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(headerReloadData) name:@"RealoadChangeSuccessNotice" object:nil];
    // Do any additional setup after loading the view.
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [_bgView removeFromSuperview];
    [_choiceView removeFromSuperview];
}
-(void)setNavgationBackBtn{
    WS(weakSelf)
    [super setNavgationBackBtn];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:[UIImage imageNamed:@"add_orderchek"] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    [btn addTarget:self action:@selector(presentChooseVc) forControlEvents:UIControlEventTouchUpInside];
    _titleBtn = [LKBaseButton buttonWithFrame:CGRectMake(0, 0, 150, 40) type:UIButtonTypeCustom title:@"我提交的申请" titleColor:COLOR_HEX(0x000000) layercorne:0 font:[UIFont systemFontOfSize:17] backgroudColor:[UIColor whiteColor] AndActionBlock:^(UIButton *btn) {
        [self showChoiceView:btn];
    }];
   [_titleBtn addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew || NSKeyValueChangeOldKey context:nil];
        self.navigationItem.titleView = _titleBtn;
//    [_titleBtn setImage:[UIImage imageNamed:@"zhankai"] forState:UIControlStateNormal];
//    CGFloat imgWidth = _titleBtn.imageView.bounds.size.width;
//    CGFloat labWidth = _titleBtn.titleLabel.bounds.size.width;
//    [_titleBtn setImageEdgeInsets:UIEdgeInsetsMake(0, labWidth, 0, -labWidth)];
//    [_titleBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -imgWidth, 0, imgWidth)];

}
-(void)presentChooseVc{
    WS(weakSelf)
    LKMyChooseCheckTypeViewController *vc = [[LKMyChooseCheckTypeViewController alloc] initWithNibName:@"LKMyChooseCheckTypeViewController" bundle:nil];
    [vc.pushSubject subscribeNext:^(id  _Nullable x) {
        [weakSelf.navigationController pushViewController:x animated:YES];
    }];
    [vc.cancelSubject subscribeNext:^(id  _Nullable x) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
//    [self.navigationController pushViewController:vc animated:YES];
    [self presentViewController:vc animated:YES completion:nil];
}

-(void)showChoiceView:(UIButton *)btn{
    WS(weakSelf);
    if (!_bgView) {
        self.bgView = [[UIView alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, WIDTH, HEIGHT - NAVIGATION_BAR_HEIGHT)];
        self.bgView.alpha = 0.5f;
        self.bgView.backgroundColor = [UIColor blackColor];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removebackView:)];
        [self.bgView addGestureRecognizer:tap];
    }
    if (!_choiceView) {
        self.choiceView = [[LKPopChoiceView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 150)];
        self.choiceView.titleArray = @[@"我提交的申请",@"待审批",@"已审批"];
        [[UIApplication sharedApplication].keyWindow addSubview:self.choiceView];
        [UIView animateWithDuration:0.5 animations:^{
            _choiceView.frame = CGRectMake(0,NAVIGATION_BAR_HEIGHT,WIDTH ,150);
        }];
    }
    self.choiceView.valueBlock = ^(NSString *title) {
        [btn setTitle:title forState:UIControlStateNormal];
        CGFloat imgWidth = btn.imageView.bounds.size.width;
        CGFloat labWidth = btn.titleLabel.bounds.size.width;
        [btn setImageEdgeInsets:UIEdgeInsetsMake(0, labWidth, 0, -labWidth)];
        [btn setTitleEdgeInsets:UIEdgeInsetsMake(0, -imgWidth, 0, imgWidth)];
        [weakSelf.dataListArray removeAllObjects];
        [weakSelf getMyCheckInforWithTitle:title];
        [weakSelf.tableView reloadData];
        [weakSelf.bgView removeFromSuperview];
        
    };
    [[UIApplication sharedApplication].keyWindow addSubview:self.bgView];
    [[UIApplication sharedApplication].keyWindow addSubview:self.choiceView];
    [UIView animateWithDuration:0.5 animations:^{
        _choiceView.frame = CGRectMake(0,NAVIGATION_BAR_HEIGHT,WIDTH ,150);
    }];
}
-(void)removebackView:(UITapGestureRecognizer *)tap{
    [UIView animateWithDuration:0.5 animations:^{
        UIView *view = tap.view;
        [view removeFromSuperview];
        [_choiceView removeFromSuperview];
    }];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataListArray.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([_titleBtn.titleLabel.text isEqual:@"我提交的申请"]) {
        LKMyCommitApplyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LKMyCommitApplyCell"];
        cell.approModel = self.dataListArray[indexPath.section];
        return cell;
    }
    if ([_titleBtn.titleLabel.text isEqual:@"待审批"]) {
        LKMyWaitingCheckCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LKMyWaitingCheckCell"];
        cell.applyModel = self.dataListArray[indexPath.section];
        return cell;
    }
    LKMyCommitApplyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LKMyCommitApplyCell"];
    cell.approModel = self.dataListArray[indexPath.section];
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    if ([_titleBtn.titleLabel.text isEqual:@"已审批"]) {
//        return 164;
//    }
//    if ([_titleBtn.titleLabel.text isEqual:@"待审批"]) {
//        return 164;
//    }
    return 130;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.0000000000001;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 13;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [[UIView alloc] init];
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = cellHeaderBgColor;
    return view;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([_titleBtn.titleLabel.text isEqual:@"我提交的申请"]) {
        LKApprovaModel *model = self.dataListArray[indexPath.section];

        if (model.customerName) {
            LKMyWorkerCheckViewController *vc = [[LKMyWorkerCheckViewController alloc] init];
            vc.applyId = model.Id;
            vc.type = model.customerName != nil ? @"客户归属申请":@"订单续投申请";
            vc.type = @"0";
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            LKMyOrderCheckDetailViewController *vc = [[LKMyOrderCheckDetailViewController alloc] init];
            vc.applyId = model.Id;
            vc.type = @"订单续投申请";
            vc.type = @"1";
            [self.navigationController pushViewController:vc animated:YES];
        }
    }else if ([_titleBtn.titleLabel.text isEqual:@"待审批"]){
        LKMyUpdateCustomerCheckViewController *vc = [[LKMyUpdateCustomerCheckViewController alloc] init];
        LKApprovaModel *model = self.dataListArray[indexPath.section];
        vc.approvModel = model;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        LKMyUpdateCustomerCheckResultViewController *vc = [[LKMyUpdateCustomerCheckResultViewController alloc] init];
        vc.approvModel = self.dataListArray[indexPath.section];
        [self.navigationController pushViewController:vc animated:YES];
    }

}
-(UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView{
    return [UIImage imageNamed:@"empty_orderchek"];
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if (object == _titleBtn) {
        if ([keyPath  isEqual: @"title"]) {
            [self.tableView reloadData];
        }
    }
}
-(NSMutableArray *)dataListArray{
    if (!_dataListArray) {
        _dataListArray = [[NSMutableArray alloc] init];
    }
    return _dataListArray;
}
//获取申请消息
-(void)getMyCheckInforWithTitle:(NSString *)title{
    NSString *url;
    if ([title containsString:@"审批"]) {
        url = getMyCheckUrl;
    }else{
        url = getMyApplyUrl;
    }
    NSString *pageIndexStr = [NSString stringWithFormat:@"%ld",self.PageIndex];
    NSString *maxRsult = [NSString stringWithFormat:@"%ld",self.MaxResultCount];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:pageIndexStr,@"PageIndex",maxRsult,@"MaxResultCount",[self accordingTileBackType:title],@"ApprovarStatu", nil];
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:url header:[LKUserInforTool header] parameters:param progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        if (self.PageIndex == 1) {
            [self.dataListArray removeAllObjects];
        }
        NSArray *itmesArra = responseObject[@"result"][@"items"];
        for (NSDictionary *dic in itmesArra) {
            LKApprovaModel *model = [LKApprovaModel modelWithDictionary:dic];
            [self.dataListArray addObject:model];
        }
//        if (self.dataListArray.count == 0) {
//            self.tableView.mj_footer.hidden = YES;
//        }
       [self.tableView reloadData];
    } failure:^(NSString * _Nullable errorMessage) {
        
    }];

}

/**
 根据文字返回传值类型

 */
-(NSString *)accordingTileBackType:(NSString *)title{
    if ([title isEqual:@"待审批"]) {
        return @"0";
    }else if ([title isEqual:@"已审批"]){
        return @"1";
    }else{
        return @"";
    }
}
-(void)dealloc{
    [self.titleBtn removeObserver:self forKeyPath:@"title"];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
